<template>
  <div class="flex h-full">
    <a-card class="mr-2" :body-style="{ height: '100%', display: 'flex', flexDirection: 'column' }">
      <PatientListDrawer
        :patient-list="patientList"
        :selected-item="selectedItem"
        :loading="patientListLoading"
        :border-bottom="false"
        @select="selectPatient"
        @refresh="getInpRecordList"
      >
        <template #search>
          <div class="w-full px-2">
            <SelectArea
              v-model:value="searchParams.bqid"
              use-cache
              class="w-full"
              post-url
              :post-params="{ wardTypeCodes: ['QYLB001', 'QYLB002'] }"
              @change="getInpRecordList"
            />
          </div>
        </template>
        <template #tabRadio>
          <div class="p-2 w-full -mt-2 border-b">
            <a-input-search
              v-model:value="searchParams.zjm"
              class="w-full"
              placeholder="姓名/助记码/床位号"
              @search="getInpRecordList()"
              @change="getInpRecordList()"
            />
          </div>
        </template>
      </PatientListDrawer>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <PatientInfoHeader :patient-info="selectedItem">
        <template #prefix>
          <div class="text-2xl pr-4 text-primary font-semibold">{{ selectedItem.bedCode }}床</div>
        </template>
        <a-divider type="vertical" :style="{ height: '40px', margin: '0 16px' }" />
        <div>
          <div class="flex items-center">
            <LabelValue label="住院科室" :width="200" :value="selectedItem.ksmc" />
            <LabelValue label="住院号" :width="220" :value="selectedItem.admissionCode" />
            <!-- <LabelValue label="过敏史" :width="200" :value="selectedItem.brGms" /> -->
            <AllergyHistory :width="200" :value="selectedItem.brGms" :patient-info="selectedItem" @success="(e) => (selectedItem.brGms = e)" />
            <LabelValue label="保险信息" :width="200" :value="selectedItem.bxxx" />
            <LabelValue label="住院天数" :width="160" :value="selectedItem.zyts" />
          </div>
          <div class="flex items-center">
            <LabelValue label="住院病区" :width="200" :value="selectedItem.wardName" />
            <LabelValue label="入区时间" :width="220" :value="selectedItem.lastDeptRegTime" />
            <LabelValue label="账户余额" :width="200" :value="formatAmount(selectedItem.yjje) || 0 + '元'" />
            <LabelValue label="入院诊断" :width="160" :value="selectedItem.ryzd" />
          </div>
        </div>
      </PatientInfoHeader>
      <div class="flex flex-1 mt-2 overflow-hidden">
        <a-card class="flex-1 overflow-hidden" :body-style="{ padding: '0 8px', height: '100%', overflow: 'hidden' }">
          <div class="flex justify-between mt-2" :class="{ 'disabled-style': patientListLoading || loading }">
            <div class="flex items-center">
              <a-input-search v-model:value="formState.keyword" allow-clear class="ml-2 w-56" placeholder="项目名称/助记码" @search="getData" />
              <a-range-picker v-model:value="formState.dateRange" format="YYYY-MM-DD" class="ml-2 w-60" value-format="YYYY-MM-DD" @change="getData" />
              <a-radio-group v-model:value="formState.advExecType" class="ml-4" @change="getData">
                <a-radio value="">全部</a-radio>
                <a-radio :value="1">长期</a-radio>
                <a-radio :value="0">临时</a-radio>
                <a-radio :value="2">出院带药</a-radio>
              </a-radio-group>
            </div>
            <a-space>
              <BaseExport
                type="住院"
                name="费用核对"
                code="000110'"
                :search-params="{ inplsh: selectedItem.inplsh, keyword: formState.keyword, advExecType: formState.advExecType }"
              >
                导出
              </BaseExport>
              <a-button
                :disabled="selectedItem.status !== 0 || selectedItem.chargeStatus !== 0"
                type="primary"
                :loading="hospitalLoading"
                @click="onHospitalCharge()"
                >当日出院补费</a-button
              >
              <a-button
                v-if="allAuditFlag"
                :disabled="allAuditDisabled !== 0 || selectedItem.status !== 0 || selectedItem.chargeStatus !== 0"
                type="primary"
                @click="allAuditStatus(2, 3)"
                >全部审核</a-button
              >
              <BaseButton
                v-else
                :disabled="selectedItem.status !== 0 || selectedItem.chargeStatus !== 0"
                danger
                confirm-text="确认全部撤销审核?"
                type="primary"
                @click="allAuditStatus(3, 2)"
              >
                全部撤审
              </BaseButton>
            </a-space>
          </div>
          <BaseTable
            class="mt-2"
            :loading="loading"
            column-code="000855"
            row-key="uid"
            :scroll="{ x: 1900 }"
            :data-source="dataSource"
            max-fill
            :extra-height="50"
            :expanded-row-keys="expandedRowKeys"
            @expand="onTableExpand"
          >
            <template #emptyText> <span>-</span> </template>
            <template #expandIcon="{ expanded, record, onExpand }">
              <component :is="expanded ? CaretDownOutlined : CaretRightOutlined" v-if="record.children?.length" @click="onExpand(record, $event)" />
            </template>
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'status'">
                <a-tag v-if="record.status === 2" color="blue">未审核</a-tag>
                <a-tag v-else-if="record.status === 3" color="green">已审核</a-tag>
                <span v-else>-</span>
              </template>
              <template v-if="column.dataIndex === 'action' && selectedItem.status === 0 && selectedItem.chargeStatus === 0">
                <template v-if="!['2', '4', '5'].includes(record.advTypeCode)">
                  <a-button
                    v-if="record.level === 1 || record.level === 2"
                    :disabled="record.status === 3"
                    type="link"
                    size="small"
                    @click="changeAuditStatus(record.expenseIds, 3)"
                  >
                    审核
                  </a-button>
                  <template v-else>
                    <a-button v-if="record.status === 2" type="link" size="small" @click="changeAuditStatus([record.id], 3)"> 审核 </a-button>
                    <BaseButton
                      v-if="record.status === 3"
                      danger
                      confirm-text="确认撤销审核?"
                      type="link"
                      size="small"
                      @click="changeAuditStatus([record.id], 2)"
                    >
                      撤审
                    </BaseButton>
                    <a-button :disabled="record.status === 3" type="link" size="small" @click="onCancelCost(record)">撤销费用</a-button>
                  </template>
                </template>
              </template>
            </template>
            <template #footer>
              <div class="flex py-4 px-2 border-t border-gray-200">
                <div class="mr-2">总费用：{{ formatAmount(dataTotal) }}</div>
                <!-- <template v-for="item in categoryFeeData" :key="item.advTypeName">
                  <div v-if="item.amount" class="mr-3">{{ item.advTypeName }}：{{ formatAmount(item.amount) }}</div>
                </template> -->
              </div>
            </template>
          </BaseTable>
        </a-card>
      </div>
    </div>
    <Edit v-model:open="open" :row-data="rowData" :selected-item="selectedItem" @success="getData" />
  </div>
</template>

<script setup>
import { message } from 'ant-design-vue'
import { useRoute } from 'vue-router'
import dayjs from 'dayjs'
import { CaretDownOutlined, CaretRightOutlined } from '@ant-design/icons-vue'
import BaseTable from '@/components/BaseTable'
import PatientInfoHeader from '@/components/business/PatientInfoHeader'
import PatientListDrawer from '@/components/business/PatientListDrawer'
import LabelValue from '@/components/LabelValue'
import { formatAmount } from '@/utils/format'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'
import Edit from './Edit'

const route = useRoute()
const columnCodeR = ref('000342')
const loading = ref(true)
const dataSource = ref([])
const dataTotal = ref(0)
const formState = ref({
  keyword: undefined,
  advExecType: '',
  dateRange: [dayjs().subtract(7, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})
const searchParams = ref({
  bqid: '',
  zjm: ''
})
const patientList = ref([])
const selectedItem = ref({})
const open = ref(false)
const rowData = ref({})
const allAuditFlag = ref(true)
const patientListLoading = ref(true)

//获取左侧列表数据
const getInpRecordList = async () => {
  formState.value.advTypeCodes = undefined
  formState.value.keyword = ''
  patientListLoading.value = true
  selectedItem.value = {}
  const { code, data, msg } = await post('/inp/inpComprehensive/getInpRecordInfo', {
    bqid: searchParams.value.bqid,
    zjm: searchParams.value.zjm
  })
  patientListLoading.value = false
  if (code !== 0) return message.error(msg)
  patientList.value = data
  if (data && data.length > 0) {
    if (route.query?.inplsh) {
      const itemVal = data.filter((item) => item.inplsh === route.query?.inplsh)
      itemVal.length && (selectedItem.value = itemVal[0])
    } else {
      selectedItem.value = data[0]
    }
    selectedItem.value?.inplsh && getData()
    selectedItem.value?.inplsh && getAdvTypeData()
  }
}
//选中的数据
const selectPatient = (patient) => {
  selectedItem.value = patient
  formState.value.dateRange = [dayjs().subtract(7, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
  formState.value.keyword = ''
  formState.value.advExecType = ''
  getData()
}
const allAuditDisabled = ref(0)
//获取数据
const getData = async () => {
  if (!selectedItem.value.inplsh) return
  // getFeeData()
  loading.value = true
  const res = await post('/inp/inpComprehensive/getTreePatientBillList', {
    inplsh: selectedItem.value.inplsh,
    ...formState.value,
    stdate: formState.value.dateRange?.[0],
    eddate: formState.value.dateRange?.[1]
  })
  loading.value = false
  if (res.code !== 0) return message.error(res.msg || '获取数据失败')
  if (!res.data.length === 0) return (dataSource.value = [])
  dataTotal.value = res.data.reduce((total, item) => total + item.current.amount, 0)
  dataSource.value = res.data.map((item, index) => ({
    ...item.current,
    uid: 1 + item.current.description + index,
    level: 1,
    children: item.children?.map((child, index) => ({
      ...child.current,
      level: 2,
      uid: 2 + child.current.id + index,
      children: child.children?.map((it, index) => ({
        ...it.current,
        level: 3,
        uid: 3 + it.current.id + index
      }))
    }))
  }))
}
//   mergeTable.value = res.data
//   //类别费用
// const getFeeData = async () => {
//   const feeRes = await post('/inp/inpComprehensive/getPatientBillList', {
//     inplsh: selectedItem.value.inplsh,
//     ...formState.value,
//     stdate: formState.value.dateRange?.[0],
//     eddate: formState.value.dateRange?.[1],
//     statusList: [2, 3]
//   })
//   dataTotal.value = feeRes.data.amount
// }
//   loading.value = false
//   if (feeRes.code !== 0) return message.error(feeRes.msg || '获取数据失败')
//   dataSource.value = feeRes.data.patientBillList || []
//   allAuditDisabled.value = feeRes.data.chargeStatus
//   dataSource.value = dataSource.value.map((it) => {
//     return { ...it, advOrderType: 0 }
//   })
//   categoryFeeData.value = feeRes.data.patientBillTypeList
//   const flag = dataSource.value.filter((it) => {
//     return it.status === 2
//   })
//   if (flag.length > 0 || dataSource.value.length === 0) {
//     allAuditFlag.value = true
//   } else {
//     allAuditFlag.value = false
//   }
// }
const expandedRowKeys = ref([])
const onTableExpand = (expanded, record) => {
  if (expanded) {
    if (record.level === 1) {
      expandedRowKeys.value = []
    }
    expandedRowKeys.value.push(record.uid)
  } else {
    expandedRowKeys.value = expandedRowKeys.value.filter((it) => it !== record.uid)
  }
}
const allAuditStatus = (status, type) => {
  const ids = []
  if (dataSource.value.length <= 0) return message.error('暂无数据')
  dataSource.value.forEach((item) => {
    if (item.status === status) ids.push(...item.expenseIds)
  })
  changeAuditStatus(ids, type)
}
const changeAuditStatus = async (ids, status) => {
  const res = await post('/inp/inpComprehensive/doUpdatelnpExpensesStatus', {
    ids: ids,
    status: status,
    inplsh: selectedItem.value.inplsh
  })
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success(res.msg || '操作成功')
  getData()
}
const advTypeOptions = ref([])
const getAdvTypeData = async () => {
  const { data, code } = await post('/inp/inpComprehensive/getAdvCodeTypes', { inplsh: selectedItem.value.inplsh })
  if (code !== 0) return
  advTypeOptions.value = data.map((item) => {
    return {
      label: item.advTypeName,
      value: item.advTypeCode
    }
  })
}
const hospitalLoading = ref(false)
const onHospitalCharge = async () => {
  const res = await post(
    '/inp/inpComprehensive/doSaveZyBf',
    {
      inplsh: selectedItem.value.inplsh,
      jslb: 'SF'
    },
    {
      hospitalLoading: true
    }
  )
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  getData()
}
const onCancelCost = (record) => {
  rowData.value = record
  open.value = true
}

onMounted(() => {
  getInpRecordList()
  if (getSystemConfig('INP_CHARGE_ENTER_ACCOUNT_MODE') === '0') {
    //住院费用依据
    columnCodeR.value = '000342'
  } else {
    columnCodeR.value = '000344'
  }
})
</script>
<style lang="less" scoped>
.w-500 {
  width: 500px;
}
.bg-color {
  background: var(--thin-color);
}
:deep(.ant-table-footer) {
  padding: 0 !important;
}
:deep(.ant-table-cell) {
  &:empty::after {
    content: '-';
  }
}
// :deep(.ant-table-row-expand-icon) {
//   display: none;
// }
.classify-checkall {
  .ant-tag {
    font-size: 14px;
    line-height: 30px;
    padding-inline: 14px;
  }
}
</style>
